import TWEEN from '@tweenjs/tween.js'

export const useTween = () => {
  const start = ({
    total = 1000,
    time = 1000 * 10,
    cb,
    complete,
  }: {
    total?: number
    time?: number
    cb: Function
    complete?: Function
  }) => {
    new TWEEN.Tween({
      number: 0,
    })
      .easing(TWEEN.Easing.Quadratic.Out)
      .to(
        {
          number: total,
        },
        time
      )
      .onUpdate((val) => {
        cb(val, total)
      })
      .start()
      .onComplete(() => {
        console.log('complete')
        complete && complete()
        TWEEN.removeAll()
      })

    function animate() {
      if (TWEEN.update()) {
        requestAnimationFrame(animate)
      }
    }
    animate()
  }

  const removeAll = () => {
    TWEEN.removeAll()
  }

  return {
    start,
    removeAll,
  }
}
